package com.example.coroutinelearn.down_load_demo

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

/**
 * @author huangzehui
 * @date 7/6/2024 下午11:17 周五
 * @description flow 与文件下载的应用
 *
 * https://www.bilibili.com/video/BV1uo4y1y7ZF?p=96&spm_id_from=pageDriver&vd_source=e07cc8cc94eb22bd76722071b03cd199
 */
class DownLoadActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val file = File(getExternalFilesDir(null), "hello.jpg")

        // lifecycleScope.launchWhenCreated 过期的替代方案
        // https://blog.csdn.net/qq_14876133/article/details/134378642
//        lifecycleScope.launchWhenCreated {  }

//        lifecycleScope.launch(Dispatchers.IO) {
//            lifecycle.repeatOnLifecycle(Lifecycle.State.CREATED) {
//
//            }
//        }

        val picUrl = "https://univs-news-1256833609.file.myqcloud.com/resource_files/cont_pub/I/AIJOI/J3SLIQIDP5BOND3A2T57W6BTOI.png"

        val flow =  DownloadManager.download(picUrl, file)

        lifecycleScope.launch {
            flow.flowWithLifecycle(lifecycle, Lifecycle.State.CREATED)
                .collect {
                    when (it) {
                        is DownloadState.Progress -> {
                            Log.e("young_test9090909","progress=${it.progress} max=${it.max}")
                        }
                        is DownloadState.Error->{
                            Log.e("young_test9090909","error = ${it.throwable}")
                        }
                        is DownloadState.Done->{
                            Log.e("young_test9090909","done = ${it.file}")
                        }
                    }
                }
        }

//        lifecycleScope.launch {
//            flow.flowWithLifecycle(lifecycle, Lifecycle.State.CREATED)
//                .collect {
//                    when (it) {
//                        is DownloadState.Progress -> {
//                            Log.e("young_test9090909","11111progress=${it.progress} max=${it.max}")
//                        }
//                        is DownloadState.Error->{
//                            Log.e("young_test9090909","2222error = ${it.throwable}")
//                        }
//                        is DownloadState.Done->{
//                            Log.e("young_test9090909","222done = ${it.file}")
//                        }
//                    }
//                }
//        }


    }

}